<?php
/* [DoYouHaoBaby!] (C)Dianniu From 2010.
   PHP_Desktop相关功能 ($)*/

!defined('DYHB_PATH') && exit;

class Phpdesktop{

	const PHPDESKTOP_ENV_VARNAME='PHPDESKTOP';
	const PHPDESKTOP_GCONFD2_ENV_VARNAME='PHPDESKTOP_GCONFD2';

	static public function runScript($sScriptPath,array $arrArgs=array(),$bUseGConfD2=false){
		if(!self::hasInstalled()){// 检查PHPDESKTOP是否安装
			G::E(G::L("PHP_Desktop尚未安装。",'LibGtk'));
		}
		$sPhpdesktop=self::getExcutor();// 获得PHPDESKTOP路径
		$sGetGConfD2=$bUseGConfD2?self::getGConfD2():null;
		foreach($arrArgs as &$sArg){// 整理参数格式
			if(preg_match('/^[\'"].*[\'"]$/s',$sArg)){
				$sArg="\"{$sArg}\"";
			}
		}
		$sArgs=' '.implode(' ',$arrArgs);
		if($sGetGConfD2===null){
			$sCmd="\"$sPhpdesktop\" -f \"{$sScriptPath}\"{$sArgs}";
		}
		else{
			$sCmd="\"{$sGetGConfD2}\" \"$sPhpdesktop\" -f \"{$sScriptPath}\"{$sArgs}";
		}
		$arrOutputLines=array();
		exec($sCmd,$arrOutputLines);
		return implode("\r\n",$arrOutputLines);
	}

	static public function hasInstalled(){
		$sPhpdesktop=self::getExcutor();
		if(!is_file($sPhpdesktop)){
			return false;
		}
		if(!is_executable($sPhpdesktop)){
			return false;
		}
		return true;
	}

	static public function getExcutor(){
		if(!isset($_ENV[self::PHPDESKTOP_ENV_VARNAME])){
			return null;
		}
		return $_ENV[self::PHPDESKTOP_ENV_VARNAME];
	}

	static public function getGConfD2(){
		if(!isset($_ENV[self::PHPDESKTOP_GCONFD2_ENV_VARNAME])){
			return null;
		}
		return $_ENV[self::PHPDESKTOP_GCONFD2_ENV_VARNAME];
	}

}
